package it.unicam.fishpass.prism.parser;

import java.util.ArrayList;

public class Utility {

	/**
	 * Searches the index of the passed variable: clocks and variables are
	 * ordered as they are ordered in the passed <code>Declaration</code> data
	 * structure.
	 */
	static int getLiteralIndex(String var, Declaration[] decs) {
		// 1 search variable
		for (int i = 0; i < decs.length; i++)
			if (var.equalsIgnoreCase(decs[i].getVar()))
				return i;
		throw new IllegalArgumentException("Variabile " + var + " non definita");
	}

	static float getLiteralValue(String var, Declaration[] decs, int[] clocks,
			float[] variables) {
		// 1 search variable
		for (int i = 0; i < decs.length; i++) {
			if (var.equalsIgnoreCase(decs[i].getVar())) {
				if (i >= clocks.length)
					return variables[i % clocks.length];
				return clocks[i];
			}
		}
		throw new IllegalArgumentException("Variabile " + var + " non definita");
	}

	static int getClockValue(String var, Declaration[] decs, int[] clocks,
			float[] variables) {
		return (int) getLiteralValue(var, decs, clocks, variables);
	}

	static boolean getBoolValue(String var, Declaration[] decs, int[] clocks,
			float[] variables) {
		return getLiteralValue(var, decs, clocks, variables) > 0;
	}

	static void ApplyResets(int[] clocks, ArrayList<Integer> resettableClocks) {
		if (resettableClocks != null) {
			for (Integer clock : resettableClocks)
				clocks[clock.intValue()] = 0;
		}
	}

	static void ApplyAssignments(ArrayList<Assign> assigns, Declaration[] decs,
			int[] clocks, float[] vars) {
		if (assigns != null) {
			for (Assign a : assigns) {
				int assignResult = a.doAssignment(decs, clocks, vars);
				int index = getLiteralIndex(a.getVar(), decs);
				vars[index - clocks.length] = assignResult;
				// note that variables can be bool (represented as 0 and 1):
				// there
				// should be no problem in that, except for GUI update
				// (represent
				// them as proper bool values) and when the value is fetched for
				// boolean expression evaluation.
			}
		}
	}
}
